package yanc.app

import grails.converters.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest

class NewsController {
    def newsService
    static final Logger logger = LoggerFactory.getLogger(NewsController.class)

    def get() {
        def data = [:]
        def list = []
        MultipartFile mf = null
        File mff = null
        if (!(request instanceof MultipartHttpServletRequest)) {
            String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' "
            log.error(errorMsg)

            throw new RuntimeException(errorMsg)
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request
        List<MultipartFile> multipartFiles = multipartRequest.getFiles("images")
        if (null != multipartFiles && multipartFiles.size() > 0) {
            mf = multipartFiles.get(0)
            def filePath = request.getSession().getServletContext().getRealPath("assets/${new Date().format("yyyyMMdd")}/")
            File f = new File(filePath)
            if (!f.exists()) {
                f.mkdirs()
            }
            def logoName = mf.getOriginalFilename()
            def fileSuffix = logoName.substring(logoName.lastIndexOf("."))
            def fileName = "${new Date().format("yyyyMMddHHmmss")}${fileSuffix}"
            def file = new File("${filePath}${fileName}")
            mf.transferTo(file)
            def path = "${new Date().format("yyyyMMdd")}/" + fileName
            def paths = newsService.getPath(path)
            list.add(paths)
//            data << [url: "http:localhost:8081/api/assets/person.png"]
            data << [errno: 0, data: list]
            render data as JSON

        }
    }

    def del() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def id = "${params.id ?: ''}"
        try {
            newsService.del(id)
            def list = News.list(max: pagesize, offset: (page - 1) * pagesize)
            def length = News.count()
            data << [statuCode: "0", errMsg: "0", data: list, total: length]
            render data as JSON
        } catch (Exception e) {
            logger.error("NewsController del Exception" + e.message)
        }
    }

    def getAll() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def title = "${params.title ?: ''}"
        try {
            def a = News.createCriteria()
            def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
                and {
                    if (!title.isEmpty()) {
                        ilike("title", "%${title}%")
                    }
                }
                order("modifyDate", "desc")
            }

            def b = News.createCriteria()
            def length = b.get {
                and {
                    if (!title.isEmpty()) {
                        ilike("title", "%${title}%")
                    }
                }
                projections {
                    rowCount()
                }
            }
            if (list) {
                data << [statuCode: "0", errMsg: "0", data: list, total: length]
            } else {
                data << [statuCode: "1", errMsg: "1"]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("CommController Exception " + e.message)
        }
    }

    def add() {
        def data = [:]
        def json = request.JSON
        def subTitle = json.subTitle
        def title = json.title
        def content = json.content
        def status = json.status
        def order = json.orders
//        def iconUrl = "${params.iconUrl ?: ''}"
        try {
            def news = new News()
            news.subTitle = subTitle
            news.title = title
            news.content = content
            news.status = status
            news.orders = order
            newsService.add(news)
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            e.printStackTrace()
            logger.error("NewsController add Exception" + e.message)
        }
    }

    def refresh() {
        def data = [:]
        def json = request.JSON
        def subTitle = json.subTitle
        def id = json.id
        def title = json.title
        def content = json.content
        def status = json.status
        def order = json.orders
        try {
            def news = News.findById(id)
            news.subTitle = subTitle
            news.title = title
            news.content = content
            news.status = status
            news.orders = order
            newsService.refresh(news)
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("NewsController refresh Exception" + e.message)
        }
    }

    def getAlls() {
        def data = [:]
        def list = News.list()
        data << [statuCode: "0", errMsg: "0", data: list]
        render data as JSON
    }

    def getNews() {
        def id = "${params.id ?: ''}"
        try {
            def types = Types.findById(id)
            if (types) {
                render(view: "/show", model: [data: types.news,state: types.types])
            }else {
                render("该新闻已删除")
            }
        } catch (Exception e) {
            logger.error("NewsController Exception " + e.message)
        }
    }
}